﻿using System.Text;
using HK.Core.Common.Data;
using HK.Core.Encryption.Protocol;
using HK.Core.IO.Protocol.Output;
using HK.Core.Utils;

namespace HK.Core.IO.Output
{
    /// <summary>
    /// 文件I/O协议 - Json - Aes
    /// </summary>
    /// <typeparam name="TData">数据类型</typeparam>
    public class JsonAesFileIO<TData> : FileIO<TData>, IEncryptFileIo<TData>
        where TData : JsonData, IBinaryEncrypt
    {
        
#region Create

        /// <summary>
        /// 文件I/O协议(Json - Aes)对象
        /// </summary>
        /// <param name="iJson">Json数据对象</param>
        /// <param name="iEncoding">字节编码</param>
        /// <param name="iPath">路径</param>
        /// <param name="iSecretKey">路径</param>
        /// <typeparam name="TData">数据类型</typeparam>
        /// <returns>加密文件I/O对象</returns>
        public static JsonAesFileIO<TData> Create<TData>(TData iJson, Encoding iEncoding, 
            string iPath, string iSecretKey)
            where TData : JsonData, IBinaryEncrypt
        {
            return new JsonAesFileIO<TData>
            {
                Mode = FileIoMode.Json, Encoding = iEncoding,
                Data = iJson, Path = iPath, SecretKey = iSecretKey
            };
        }

#endregion
        
        /// <summary>
        /// 保护构造函数
        /// </summary>
        private JsonAesFileIO() {}


        /// <summary>
        /// 密钥
        /// </summary>
        public string SecretKey { get; private set; } = null;

#region Import

        /// <summary>
        /// 执行导入
        /// </summary>
        /// <returns>true:OK; false:NG;</returns>
        protected override bool DoImport()
        {
            var tokenStr = System.IO.File.ReadAllText(Path);
            if (string.IsNullOrEmpty(tokenStr)) return false;

            var importData = UtilsEncrypts.Decode<TData>(Path, EncryptOption.Aes, Encoding, SecretKey);
            if (default(TData) == importData || !importData.Valid) return false;

            // 数据
            Data = importData;
            return true;
        }

#endregion

#region Export
        
        /// <summary>
        /// 执行导入
        /// </summary>
        /// <returns>true:OK; false:NG;</returns>
        protected override bool DoExport()
        {
            if (!UtilsEncrypts.Encode(Path, Data, EncryptOption.Aes, Encoding, SecretKey))
            {
                Error("DoExport():UtilsEncrypts.Encode() Failed!(Path:{0})", Path);
                return false;
            }
            return true;
        }

#endregion
        
    }
}